package com.alan.netty.nio.channels;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * 把它理解为 TCP 连接通道，简单理解就是 TCP 客户端
 *
 * @author weiBin
 * @date 2018/11/7
 */
public class SocketChannelAccess {
    private static final String MSG = "hello, I am coming!";

    public static void main(String[] args) throws IOException, InterruptedException {

        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8081);
        SocketChannel sc = SocketChannel.open();
        sc.connect(inetSocketAddress);
        sc.configureBlocking(false);

        while (!sc.finishConnect()) {
            System.out.println("等待连接服务器");
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("获取到服务器连接:");
        ByteBuffer writeBuffer = ByteBuffer.wrap(MSG.getBytes());
        sc.write(writeBuffer);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            buffer.clear();
            int i = sc.read(buffer);
            if (i == -1) {
                sc.close();
                break;
            }
            buffer.flip();
            if (buffer.limit() == 0) {
                Thread.sleep(1500L);
            } else {
                System.out.println(new String(buffer.array()));
            }
        }

    }
}
